package org.fastsyncer.connector.ws;

import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.WebServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebServiceConnector implements WebService {

	private final Logger LOG = LoggerFactory.getLogger(WebServiceConnector.class);

	private static WebServiceConnector instance = null;

	public WebServiceConnector() {
	}

	/**
	 * 建议使用该方法
	 * 
	 * @return WebServiceConnector
	 */
	public static WebServiceConnector getInstance() {
		if (instance == null) {
			synchronized (WebServiceConnector.class) {
				instance = new WebServiceConnector();
			}
		}
		return instance;
	}

	/**
	 * 判断URL是否可用
	 * 
	 * @Title: isAlive
	 * @Description: 判断URL是否可用
	 * @param config
	 *            Webservice配置
	 * @throws IllegalAccessException
	 * @return: boolean true: 可用 false: 不可用
	 */
	public boolean isAlive(WebServiceConfig config) throws IllegalAccessException {
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(config.getUrl()).openConnection();
			if(HttpURLConnection.HTTP_OK == connection.getResponseCode()){
				connection.disconnect();
				return true;
			}
		} catch (Exception e) {
			LOG.error("unable to connect:" + config.getUrl(), e.getMessage());
		}
		return false;
	}

	@Override
	public BaseInfo getBaseInfoConnector(WebServiceConfig config) throws IllegalAccessException {
		return new BaseInfo();
	}

	@Override
	public Object send(String url, String method, String msg) throws Exception {
		// 1.获取一个工厂实例
		JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();

		// 2.生成针对指定服务接口URL的客户端
		Client client = factory.createClient(url);

		// 3.调用指定的方法，注意入参第一个为方法名称，第二个为方法的参数（可以传入一个参数列表，一般为数组）
		Object[] objs = client.invoke(method, msg);

		// 4.关闭客户端连接
		client.destroy();

		// 5.返回响应结果
		return objs[0].toString();
	}

}
